//
//  MPBFilePath.h
//  MiaoPai
//
//  Created by jiaxuzhou on 2017/6/26.
//  Copyright © 2017年 Jeakin. All rights reserved.
//
//


#import "MPBFilePath.h"


@interface MPBFilePath ()

// 沙盒主目录
@property (nonatomic, readwrite, strong) NSString *homePath;
// 沙盒主目录下的 Documents目录（此目录下所有的数据都会通过iTunes备份）
@property (nonatomic, readwrite, strong) NSString *docmentsPath;
// 沙盒Documents目录下的db.sqlite3数据库目录
@property (nonatomic, readwrite, strong) NSString *dbPath;
// 沙盒主目录下的Library目录
@property (nonatomic, readwrite, strong) NSString *libraryPath;
// 沙盒主目录下的tmp目录 重启手机后会清空
@property (nonatomic, readwrite, strong) NSString *tmpPath;
// Library 目录下的Caches 不会通过iTunes备份
@property (nonatomic, readwrite, strong) NSString *cachesPath;
// Library 目录下的 Preferences 会通过iTunes备份
@property (nonatomic, readwrite, strong) NSString *preferencesPath;
// 主boundle目录
@property (nonatomic, readwrite, strong) NSString *bundlePath;
// Library/Caches/Download
@property (nonatomic, readwrite, strong) NSString *downloadPath;
// Library/Caches/CoreData
@property (nonatomic, readwrite, strong) NSString *coredataPath;
// Documents／media
@property (nonatomic, readwrite, strong) NSString *mediaPath;
// Documents／theme
@property (nonatomic, readwrite, strong) NSString *themePath;
// Documents／music
@property (nonatomic, readwrite, strong) NSString *musicPath;
// Documents／video
@property (nonatomic, readwrite, strong) NSString *videoPath;
// Documents／photo
@property (nonatomic, readwrite, strong) NSString *photoPath;
// Documents／paster
@property (nonatomic, readwrite, strong) NSString *pasterPath;
// Documents／opera
@property (nonatomic, readwrite, strong) NSString *operaPath;
// Documents／monkey
@property (nonatomic, readwrite, strong) NSString *monkeyPath;
// Documents／faceSticker
@property (nonatomic, readwrite, strong) NSString *faceStickerPath;
// Documents／tmpVideo
@property (nonatomic, readwrite, strong) NSString *tmpVideoPath;
// Documents／temp.plist
@property (nonatomic, readwrite, strong) NSString *tmpVideoInfoPath;
// Documents／stream
@property (nonatomic, readwrite, strong) NSString *qiniuRecorderPath;
// Documents／Inbox
@property (nonatomic, readwrite, strong) NSString *inboxPath;
// Documents／historyDiscovers.plist
@property (nonatomic, readwrite, strong) NSString *historyDiscoversPath;
// Documents／
@property (nonatomic, readwrite, strong) NSString *facePath;


@end


@implementation MPBFilePath


+ (MPBFilePath *)sharedInstance
{
    static MPBFilePath *mpFilePath = nil;
    
    if (!mpFilePath)
    {
        @synchronized(self)
        {
            if (!mpFilePath) mpFilePath = [[self alloc] init];
        }
    }
    
    return mpFilePath;
}

- (id)init
{
    self = [super init];
    
    if (self)
    {
        [self initialize];
    }
    
    return self;
}

- (void)initialize
{
    [self initDirPath];
}

- (void)initDirPath
{
    self.homePath = NSHomeDirectory();
    self.bundlePath = [[NSBundle mainBundle] bundlePath];
    
    self.docmentsPath = [self.homePath stringByAppendingPathComponent:@"Documents"];
    self.libraryPath = [self.homePath stringByAppendingPathComponent:@"Library"];
    self.tmpPath = [self.homePath stringByAppendingPathComponent:@"tmp"];
    self.cachesPath = [self.homePath stringByAppendingPathComponent:@"Library/Caches"];
    self.preferencesPath = [self.homePath stringByAppendingPathComponent:@"Library/Preferences"];
    
    self.downloadPath = [self.homePath stringByAppendingPathComponent:@"Library/Caches/Download"];
    self.coredataPath = [self.homePath stringByAppendingPathComponent:@"Library/Caches/CoreData"];
    self.mediaPath = [self.docmentsPath stringByAppendingPathComponent:@"media"];
    self.themePath = [self.docmentsPath stringByAppendingPathComponent:@"theme"];
    self.musicPath = [self.docmentsPath stringByAppendingPathComponent:@"music"];
    self.videoPath = [self.docmentsPath stringByAppendingPathComponent:@"video"];
    self.photoPath = [self.docmentsPath stringByAppendingPathComponent:@"photo"];
    self.pasterPath = [self.docmentsPath stringByAppendingPathComponent:@"paster"];
    self.operaPath = [self.docmentsPath stringByAppendingPathComponent:@"opera"];
    self.monkeyPath = [self.docmentsPath stringByAppendingPathComponent:@"monkey"];
    self.faceStickerPath = [self.docmentsPath stringByAppendingPathComponent:@"faceSticker"];
    self.tmpVideoPath = [self.docmentsPath stringByAppendingPathComponent:@"tmpVideo"];
    self.dbPath = [self.docmentsPath stringByAppendingPathComponent:@"db.sqlite3"];
    self.tmpVideoInfoPath = [self.docmentsPath stringByAppendingPathComponent:@"temp.plist"];
    self.qiniuRecorderPath = [self.docmentsPath stringByAppendingPathComponent:@"stream"];
    self.inboxPath = [self.docmentsPath stringByAppendingPathComponent:@"Inbox"];
    self.historyDiscoversPath = [self.docmentsPath stringByAppendingPathComponent:@"historyDiscovers.plist"];
    self.facePath = [self.docmentsPath stringByAppendingPathComponent:@"face"];
    
    [self createDirPathIfNeed:self.homePath];
    [self createDirPathIfNeed:self.docmentsPath];
    [self createDirPathIfNeed:self.mediaPath];
    [self createDirPathIfNeed:self.themePath];
    [self createDirPathIfNeed:self.musicPath];
    [self createDirPathIfNeed:self.videoPath];
    [self createDirPathIfNeed:self.photoPath];
    [self createDirPathIfNeed:self.tmpVideoPath];
    [self createDirPathIfNeed:self.qiniuRecorderPath];
    [self createDirPathIfNeed:self.facePath];
    
    [self addSkipBackupAttributeToItemAtPath:self.docmentsPath];
}

- (NSString *)createDirPathIfNeed:(NSString*)dirPath
{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    if (![fileManager fileExistsAtPath:dirPath])
    {
        [fileManager createDirectoryAtPath:dirPath
               withIntermediateDirectories:YES
                                attributes:nil
                                     error:NULL];
    }
    
    return dirPath;
}

- (BOOL)addSkipBackupAttributeToItemAtPath:(NSString *)filePathString
{
    NSURL* URL= [NSURL fileURLWithPath: filePathString];
    assert([[NSFileManager defaultManager] fileExistsAtPath:[URL path]]);
    
    NSError *error = nil;
    BOOL success = [URL setResourceValue:[NSNumber numberWithBool: YES]
                                  forKey:NSURLIsExcludedFromBackupKey
                                   error:&error];
    if(!success)
    {
        NSLog(@"Error excluding %@ from backup %@", [URL lastPathComponent], error);
    }
    
    return success;
}

- (void)clearInboxFilesIfNeed
{
    dispatch_queue_t dispatchQueue = dispatch_queue_create("com.miaopai.inbox.clear.queue", DISPATCH_QUEUE_CONCURRENT);
    dispatch_group_t dispatchGroup = dispatch_group_create();
    dispatch_group_async(dispatchGroup, dispatchQueue, ^(){
        NSError *error = nil;
        NSArray *files = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:self.inboxPath
                                                                             error:&error];
        
        if(error == nil)
        {
            NSDate *yesterday = [NSDate dateWithTimeIntervalSinceNow:-24*60*60];;
            for(NSString *path in files)
            {
                NSString *itemPath = [self.inboxPath stringByAppendingPathComponent:path];
                NSDictionary *properties = [[NSFileManager defaultManager] attributesOfItemAtPath:itemPath error:&error];
                
                if(error == nil)
                {
                    NSDate *date = [properties objectForKey:NSFileCreationDate];
                    NSComparisonResult result = [yesterday compare:date];
                    
                    if (result == NSOrderedDescending)
                    {
                        [[NSFileManager defaultManager] removeItemAtPath:itemPath error:nil];
                    }
                }
            }
        }
    });
}


@end
